package com.my.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: 自定义配置护院等级UserLevel，按照钻/金/银和yml配置的等级，判断是哦福可以访问
 * @date 2024/3/12 14:07
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config> {

    public MyRoutePredicateFactory(){
        super(MyRoutePredicateFactory.Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange exchange) {
                String userLevel = exchange.getRequest().getQueryParams().getFirst("userLevel");
                if (userLevel == null){
                    return false;
                }
                // 如果参数存在，与config的数据进行比较
                if (userLevel.equalsIgnoreCase(config.userLevel)){
                    return true;
                }
                // 比较不成功
                return false;
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userLevel");
    }

    // 此Config类就是路由断言规则
    @Validated
    public static class Config{
        @Setter
        @Getter
        @NotEmpty
        private String userLevel;
        
        
    }
}
